package com.example.sqlite.utils;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;

/**
 * @author evaldosavio, nayraoliviera
 * 
 */
public class EditMask implements TextWatcher {
	private final EditText edt;
	private boolean isUpdating;
	private final String mask;

	/**
	 * @param edt
	 * @date_modify Feb 23, 2013
	 * @author evaldosavio,nayraoliviera
	 */
	public EditMask(EditText edt, String mask) {
		this.edt = edt;
		this.mask = mask;
		this.edt.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
				mask.length()) });
		this.edt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					if (getMask().length() > getText().length()) {
						EditMask.this.edt.setText("");
					}
				}
			}
		});
	}

	@Override
	public void afterTextChanged(Editable arg0) {

	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	/**
	 * @author evaldosavio,nayraoliviera
	 */
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int after) {
		String text = getText();
		text = text.replaceAll("([\\W_])", "");

		if (isUpdating) {
			isUpdating = false;
			return;
		}
		isUpdating = true;

		// Se after > before significa que o usuario esta digitando, caso
		// contrario esta apagando
		if (after > before) {
			edt.setText(mountMask(text));

			if (start == getText().length()) {
				edt.setSelection(start);
				return;
			}

			char token = mask.charAt(start);
			while (token != '_' && token != '#') {
				token = mask.charAt(++start);
			}
			edt.setSelection(start + 1 <= getText().length() ? start + 1
					: start);

		} else {

			edt.setText(mountMask(text));

			if (start > getText().length()) {
				start--;
			}
			edt.setSelection(start);
		}
		isUpdating = false;
	}

	/**
	 * formatar o texto de acordo com a máscara
	 * 
	 * @data_modificacao Feb 25, 2013
	 * @author evaldosavio,nayraoliviera
	 * @param text
	 * @param str
	 * @return
	 */

	private String mountMask(String text) {
		String str = "";
		for (int i = 0, j = 0; i < text.length(); i++, j++) {
			if ("#_".contains(mask.charAt(j) + "")) {
				str += text.charAt(i);
			} else {
				str += mask.charAt(j);
				i--;
			}
		}
		return str;
	}

	private String getText() {
		return edt.getText().toString();
	}

	/**
	 * Get mask
	 * 
	 * @date_modificacao Feb 25, 2013
	 * @author evaldosavio
	 * @return the mask
	 */
	public String getMask() {
		return mask;
	}
}
